<template>
    <view class="put-sale tn-safe-area-inset-bottom">
        <tn-navbar z-index="1" index-url="/pages/mine/order/buyerOrder" fixed :bottom-shadow="false">委托上架</tn-navbar>
        <view class="order-info">
            <view class="order-item">
                <view class="item-top tn-flex-row">
                    <view class="order-sn tn-flex-2"> 订单号：{{ order.orderSn }} </view>
                    <view class="order-status tn-flex-1 tn-color-main">
                    </view>
                </view>
                <view class="item-content tn-flex-row">
                    <view class="goods-img tn-flex-2">
                        <img :src="order.goodsImg" />
                    </view>
                    <view class="goods-info tn-flex-row tn-flex-6">
                        <view class="goods-info-name tn-flex-5">
                            {{ order.goodsName }}</view>
                        <view class="goods-info-other tn-flex-column tn-flex-2">
                            <view class="goods-price">￥{{ originalPrice }}</view>
                            <view class="goods-num">x1</view>
                        </view>
                    </view>
                </view>

            </view>

            <view class="order-price-info">
                <view class="top-title">委托价格</view>
                <view class="order-price">
                    <view class="price tn-color-main">{{ price }}</view>
                    <view class="slider">
                        <tn-slider v-model="sliderValue" height="5" bar-size="50" min="1" :max="100"></tn-slider>
                    </view>

                </view>
            </view>

            <view class="order-other">
                <view class="order-other-item tn-flex-rows">
                    <view class="item-desc tn-flex-1">服务费</view>
                    <view class="item-value tn-flex-1">￥{{ servicePrice }}</view>
                </view>
            </view>
        </view>

        <view class="tools">
            <view class="order-total tn-flex-1">合计：￥{{ servicePrice }}</view>
            <view class="action tn-flex-1 tn-bg-main" @click="handlePutSale">
                确认上架
            </view>
        </view>
        <tn-toast ref="toast"></tn-toast>
    </view>
</template>
  
<script setup lang="ts">
import { onMounted, ref, reactive, computed } from "vue";

import TnNavbar from "@/tuniao-ui/components/tn-navbar/src/Navbar.vue";
import TnButton from "@/tuniao-ui/components/tn-button/src/Button.vue";
import TnIcon from "@/tuniao-ui/components/tn-icon/src/Icon.vue";
import TnToast from "@/tuniao-ui/components/tn-toast/src/Toast.vue";
import TnSlider from "@/tuniao-ui/components/tn-slider/src/Slider.vue";
import { ResultEnum } from "@/enums/httpEnum";
import { navBack } from "@/tuniao-ui/utils";
import { findRushPurchaseDetail, getOrderPriceInfo, putSaleOrder } from "@/api/purchaseDetail";
import { getStorage, setStorage, removeStorage } from "@/tuniao-ui/utils";
import { useUserStore } from "@/tuniao-ui/store/user";
import { getCodeUrl } from "@/api/weixin";
import { domain } from "@/config";
import { onLoad } from "@dcloudio/uni-app";
const userStore = useUserStore();

const toast = ref<InstanceType<typeof TnToast>>();
// slider的值
const sliderValue = ref<number>(1)
// 当前操作的活动id（订单id）
const orderId = ref(2);
const order = reactive({
    id: null,
    orderSn: "",
    goodsImg: "",
    goodsName: "",
    price: 0,
    servicePrice: 0
});
const originalPrice = ref(0);
const servicePricePre = ref<number>(0); // 服务费百分比，通过后台返回数据计算所得
// 计算中的价格和服务费
const price = computed(() => {
    // 如果是最大值 直接返回后端计算好的价格
    if (sliderValue.value == 100) {
        return order.price;
    }
    return Number((sliderValue.value * originalPrice.value / 100).toFixed(0));
});
const servicePrice = computed(() => {
    // 如果是最大值 直接返回后端计算好的价格
    if (sliderValue.value == 100) {
        return order.servicePrice;
    }
    return Number((servicePricePre.value * originalPrice.value * sliderValue.value / 100).toFixed(0));
});

const code = ref("");

/**
 * 委托上架点击事件
 *
 */
function handlePutSale() {
    //putSale();
    let suggestedPrice = Number((originalPrice.value * 1.04).toFixed(0));
    if (price.value < suggestedPrice) {
        uni.showModal({
            title: "提示",
            content: `确定要以${price.value}元的价格上架吗？`,
            success: function (res) {
                if (res.confirm) {
                    putSale();
                } else if (res.cancel) {
                    console.log('用户点击取消');
                }
            }
        });

    } else {
        putSale();
    }
}

/**
 * 订单上架
 */
function putSale() {
    let memberNo = userStore.getMemberNo;
    let key = memberNo + "_openid";
    let openid = getStorage(key);

    putSaleOrder({ id: orderId.value, code: code.value, openid: openid, price: price.value, servicePrice: servicePrice.value}).then((res) => {
        console.log(res);
        if (res.code === ResultEnum.SUCCESS) {
            // 缓存openid 下次支付时使用
            let memberNo = userStore.getMemberNo;
            let key = memberNo + "_openid";
            setStorage(key, res.result.openid);

            // 微信验证
            WeixinJSBridge.invoke(
                "getBrandWCPayRequest",
                res.result.response,
                function (result: any) {
                    if (result.err_msg == "get_brand_wcpay_request:ok") {
                        // 使用以上方式判断前端返回,微信团队郑重提示：
                        //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                        toast.value?.show({
                            title: "支付成功",
                        });


                        setTimeout(function () {
                            //navPage(toUrl.value);
                            //location.href = "#" + toUrl.value;
                            navBack();
                        }, 2000);
                    }
                }
            );
        } else {
            toast.value?.show({
                title: res.message,
            });

            getCode();
        }

    });
}

function getCode() {
    let redirectUri = encodeURIComponent(domain.h5 + "#/pages/mine/order/putSale?id=" + orderId.value);
    getCodeUrl({ redirectUri: redirectUri }).then((res) => {
        console.log(res);
        if (res.code === ResultEnum.SUCCESS) {
            location.href = res.result;
        }
    });
}

onLoad((options: any) => {
    orderId.value = options.id;
    if (!options.id) {
        location.href = "#/pages/mine/order/buyerOrder";
        return;
    }
    //getStorage
    let memberNo = userStore.getMemberNo;
    let key = memberNo + "_openid";
    let openid = getStorage(key);
    //openid ="test"
    if (openid === null) {
        // 获取微信中的code
        var url = window.location.search;
        var theRequest = new Object();
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            var strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
            }
        }

        // 如果没有code 跳转到微信获取code
        if (!theRequest["code"]) {

            getCode();
            return;
        } else {
            code.value = theRequest["code"];
        }
    }

    findRushPurchaseDetail({ id: orderId.value }).then((res) => {
        console.log(res);
        if (res.code === ResultEnum.SUCCESS) {
            let result = res.result;
            order.id = result.id;
            order.orderSn = result.orderSn;
            order.goodsName = result.goodsName;
            order.goodsImg = result.goodsImgs[0];
        }
    });

    getOrderPriceInfo({ id: orderId.value }).then((res) => {
        console.log(res);
        if (res.code === ResultEnum.SUCCESS) {
            let result = res.result;
            // order.id = result.id;
            // order.orderSn = result.orderSn;
            order.price = result.price;
            order.servicePrice = result.servicePrice;
            originalPrice.value = result.originalPrice;
            servicePricePre.value = Number((result.servicePrice / result.originalPrice).toFixed(3));
            console.log(servicePricePre.value, "服务费百分比");
        }
    });
    

});
</script>
  
<style lang="scss" scoped>
.order-info {
    padding: 20rpx;
}

.order-item {
    background-color: #fff;
    border-radius: 10rpx;
    padding-top: 10rpx;
    padding-bottom: 20rpx;

    .item-top {
        font-size: 30rpx;
        height: 70rpx;
        display: flex;
        align-items: center;
        padding-left: 20rpx;
        border-bottom: #f1f1f1 3rpx solid;

        .order-status {
            justify-content: flex-end;
            padding-right: 30rpx;
        }
    }

    .item-content {
        height: 150rpx;

        .goods-img {
            //padding: 20rpx;
            display: flex;
            align-items: center;
            justify-content: center;

            img {
                width: 130rpx;
                height: 130rpx;
                border-radius: 5rpx;
            }
        }

        .goods-info {
            display: flex;
            align-items: center;

            .goods-info-other {
                color: #999;
                text-align: end;
                padding-right: 40rpx;
            }
        }
    }
}

.order-price-info {
    background-color: #fff;
    border-radius: 10rpx;
    margin-top: 30rpx;
    padding: 20rpx;
    padding-bottom: 60rpx;

    .top-title {
        font-size: 30rpx;
    }

    .order-price {
        text-align: center;
        font-size: 35rpx;
        margin-top: 30rpx;

        .slider {
            margin-top: 40rpx;
        }
    }

}

.order-other {
    background-color: #fff;
    border-radius: 10rpx;
    margin-top: 30rpx;
    padding: 20rpx;

    &-item {
        height: 100rpx;
        align-items: center;

        .item-value {
            justify-content: flex-end;
        }
    }
}

.tools {
    background-color: #fff;
    height: 100rpx;
    width: 100%;
    position: fixed;
    bottom: 0;
    display: flex;
    align-items: center;
    font-size: 30rpx;

    .order-total {
        padding-left: 20rpx;
    }

    .action {
        align-items: center;
        justify-content: center;
        height: 100%;
        ;
    }
}
</style>
  